package com.zhiche.wms.service.certification.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.domain.mapper.certification.CertificationInfoMapper;
import com.zhiche.wms.domain.mapper.stock.SkuMapper;
import com.zhiche.wms.domain.mapper.stock.StockMapper;
import com.zhiche.wms.domain.model.certification.CertificationInfo;
import com.zhiche.wms.domain.model.stock.Sku;
import com.zhiche.wms.domain.model.sys.User;
import com.zhiche.wms.domain.model.sys.UserStorehouse;
import com.zhiche.wms.service.certification.CertificationService;
import com.zhiche.wms.service.sys.IUserService;
import com.zhiche.wms.service.sys.IUserStorehouseService;
import com.zhiche.wms.service.utils.CommonMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: caiHua
 * @Description: 合格证实现类
 * @Date: Create in 10:10 2019/9/5
 */
@Service
public class CertificationServiceImpl extends ServiceImpl<CertificationInfoMapper, CertificationInfo> implements CertificationService {

    @Autowired
    private IUserService userService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private IUserStorehouseService iUserStorehouseService;

    @Override
    public void receiveCertification (Map<String, String> param) {
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("未查询到登录用户");
        }
        //操作类型 Y 表示收取，N 表示发放
        String handleType = param.get("handleType");
        if (StringUtils.isEmpty(handleType)) {
            throw new BaseException("操作类型【handleType】不能为空！");
        }
        if (StringUtils.isEmpty(param.get("vin"))) {
            throw new BaseException("车架号【vin】不能为空！");
        }
        if (TableStatusEnum.STATUS_Y.getCode().equals(handleType)) {
            saveCertification(param.get("vin"), loginUser.getName());
        } else if (TableStatusEnum.STATUS_N.getCode().equals(handleType)) {
            if (StringUtils.isEmpty(param.get("certificationId"))) {
                throw new BaseException("参数【certificationId】不能为空！");
            }
            updateCertification(param.get("certificationId"), loginUser.getName());
        } else {
            throw new BaseException("操作类型【handleType】不合法！");
        }


    }

    @Override
    public Page<CertificationInfo> queryCertificationPage (Page<CertificationInfo> page) {
        Map<String, Object> condition = page.getCondition();
        EntityWrapper<CertificationInfo> certificationInfoEw = new EntityWrapper<>();

        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("未查询到登录用户");
        }
        //查询用户关联仓库
        List<Long> storeHouseList = new ArrayList<>();
        List<UserStorehouse> userStorehouses = iUserStorehouseService.getUserHouses();
        for (UserStorehouse storeHouse : userStorehouses) {
            storeHouseList.add(storeHouse.getStoreHouseId());
        }
        certificationInfoEw.in("wh.id", storeHouseList);
        if (!Objects.isNull(condition) && null != condition) {
            if (StringUtils.isNotEmpty((String) condition.get("certificatStatus"))) {
                certificationInfoEw.eq("wci.certificat_status", "certificatStatus");
            }
            if (condition.containsKey("receiveStartDate") && Objects.nonNull(condition.get("receiveStartDate"))) {
                certificationInfoEw.ge("wci.receive_date", condition.get("receiveStartDate"));
            }
            if (condition.containsKey("receiveEndDate") && Objects.nonNull(condition.get("receiveEndDate"))) {
                certificationInfoEw.le("wci.receive_date", condition.get("receiveEndDate"));
            }

            if (condition.containsKey("giveOutStartDate") && Objects.nonNull(condition.get("giveOutStartDate"))) {
                certificationInfoEw.ge("wci.giveout_date", condition.get("giveOutStartDate"));
            }
            if (condition.containsKey("giveOutEndDate") && Objects.nonNull(condition.get("giveOutEndDate"))) {
                certificationInfoEw.le("wci.giveout_date", condition.get("giveOutEndDate"));
            }
            if (StringUtils.isNotEmpty((String) condition.get("vin"))) {
                String[] vins = CommonMethod.setVins((String) condition.get("vin"));
                certificationInfoEw.in("wci.vin", Arrays.asList(vins)).or().like("wci.vin", (String) condition.get("vin"));
            }
        }
        certificationInfoEw.orderBy("wci.gmt_modified", false);
        List<CertificationInfo> list = baseMapper.queryCertificationPage(page, certificationInfoEw);
        return page.setRecords(list);
    }

    /**
     * 合格证发放
     *
     * @param certificationId 合格证id
     * @param name            登录用户
     */
    private void updateCertification (String certificationId, String name) {
        CertificationInfo queryResult = baseMapper.selectById(certificationId);
        if (null != queryResult) {
            if (queryResult.getCertificatNum() < 1) {
                throw new BaseException("该合格证已经被" + queryResult.getGiveoutUser() + "发放过，无需重复发放!");
            }
        }
        CertificationInfo certificationInfo = new CertificationInfo();
        certificationInfo.setCertificatNum(queryResult.getCertificatNum() - 1);
        certificationInfo.setGiveoutUser(name);
        certificationInfo.setGiveoutDate(new Date());
        certificationInfo.setId(Long.valueOf(certificationId));
        certificationInfo.setCertificatStatus(TableStatusEnum.STATUS_30.getCode());
        baseMapper.updateById(certificationInfo);
    }

    /**
     * 领取
     *
     * @param vin 车架号
     */
    private void saveCertification (String vin, String loginName) {
        CertificationInfo queryParam = new CertificationInfo();
        queryParam.setVin(vin);
        CertificationInfo certificationInfo = baseMapper.selectOne(queryParam);
        if (null != certificationInfo) {
            throw new BaseException(vin + "合格证已经收取，请重新输入！");
        }

        // 查询库存id
        Long stockId = stockMapper.queryMaxStockId(vin);

        CertificationInfo insertParam = new CertificationInfo();
        insertParam.setVin(vin);
        insertParam.setReceiveDate(new Date());
        insertParam.setReceiveUser(loginName);
        insertParam.setCertificatNum(1);
        insertParam.setCertificatStatus(TableStatusEnum.STATUS_20.getCode());
        if (null != stockId) {
            insertParam.setStockId(stockId);
        }
        baseMapper.insert(insertParam);
    }
}
